package com.mall.service.trade;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.client.trade.TradeService;
import com.mall.custom.dao.read.TradeReadMapper;
import com.mall.custom.dao.write.TradeWriteMapper;
import com.mall.pojo.Trade;
import com.mall.pojo.TradeExample;
import com.mall.pojo.TradeExample.Criteria;

@Service
public class TradeServiceImpl implements TradeService {

	private static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
	@Autowired
	private TradeReadMapper tradeReadMapper;
	
	@Autowired
	private TradeWriteMapper tradeWriteMapper;
	@Override
	public Trade getTradeByOrderId(Long orderId) {
		return this.tradeReadMapper.selectByPrimaryKey(orderId);
	}

	@Override
	public String generateOrderNo() {
		Date currentTime = new Date();
		String dateTimeStr = dateFormatter.format(currentTime);
		int random = 10000 + (int) (Math.random() * 89999);
		return dateTimeStr + random;
	}

	@Override
	public int insertTrade(Trade trade) {
		return tradeWriteMapper.insert(trade);
		
	}

	@Override
	public int updateTradeByTrade(Trade trade) {
		return this.tradeWriteMapper.updateByPrimaryKey(trade);
		
	}

	@Override
	public List<Trade> getTradeMessListByExample(TradeExample example) {
		
		return this.tradeReadMapper.selectByExample(example);
	}
	
	@Override
	public Trade getByOrderNO(String out_trade_no) {
		TradeExample example = new TradeExample();
		Criteria criteria = example.createCriteria();
		criteria.andOutTradeNoEqualTo(out_trade_no);
		List<Trade> tradeList = this.tradeReadMapper.selectByExample(example);
		if (tradeList == null || tradeList.size() <= 0) {
			return null;
		}
		return tradeList.get(0);
	}
	
	@Override
	public boolean updateById(Long id, Trade updateTrade) {
		updateTrade.setId(id);
		return tradeWriteMapper.updateByPrimaryKey(updateTrade) > 0;
	}

	@Override
	public int getTradeCount(TradeExample example) {
		return this.tradeReadMapper.countByExample(example);
	}

	@Override
	public Long getSumPriceByExample(TradeExample example) {
		return this.tradeReadMapper.sumPriceCountInTradeByTradeExample(example);
	}

	@Override
	public Integer getUserNumByExample(TradeExample example) {
		return this.tradeReadMapper.userNumsCountInTradeByTradeExample(example);
	}

	@Override
	public Trade getTradeByParentId(Long parentId) {
		TradeExample example = new TradeExample();
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		List<Trade> tradeList = this.tradeReadMapper.selectByExample(example);
		if (tradeList == null || tradeList.size() <= 0) {
			return null;
		}
		return tradeList.get(0);
	}
}
